<?php
declare (strict_types=1);

namespace app\common\model;

use think\model\relation\BelongsTo;
use \think\model\relation\HasMany;
use \think\model\relation\HasOne;

/**
 * 视频
 * Class Video
 * @package app\common\model
 */
class BusinessVideo extends Base
{
    protected $name = 'business_video';

    public function comment(): HasMany
    {
        return $this->hasMany(UserVideoComment::class, 'video_id', 'id')->with(['user'])->where('is_del', 0)->field('id,uid,video_id,video_second,comment,create_time')->order('create_time', 'desc')->limit(50);
    }

    public function business(): BelongsTo
    {
        return $this->belongsTo(Business::class, 'business_id', 'id')->field('id,title');
    }

    public function cate(): BelongsTo
    {
        return $this->belongsTo(VideoCate::class, 'cate_id', 'id')->field('id,title');
    }

    public function product(): HasOne
    {
        return $this->hasOne(Product::class, 'id', 'product_id')->field('id,title');
    }

    public function getLinkDomainAttr($value, $data)
    {
        return $data['link'] ? config('qiniu')['domain'] . $data['link'] : '';
    }

    public static function info($id, $user)
    {
        if($id){
            $info = self::with(['comment'])->where(['id' => $id, 'is_del' => 0])
                ->field('id,cover,introduce,link,tag,total_seconds,total_hit,total_comment,total_view,total_share,product_id,cate_id')
                ->append(['linkDomain'])
                ->find();
        }else{
            $info = self::with(['comment'])->where(['status' => 2, 'is_del' => 0])
                ->field('id,cover,introduce,link,tag,total_seconds,total_hit,total_comment,total_view,total_share,product_id,cate_id')
                ->append(['linkDomain'])
                ->orderRaw('rand()')
                ->find();
        }

        if($info){
            $info->is_hit = UserVideoHit::where(['uid' => $user->id, 'video_id' => $id])->count() ? 1 : 0;
            $info->red_coin = Assets::where('uid', $user->id)->value('red_coin');
        }

        return $info;
    }

    public static function accountRecord(): array
    {
        $record = [];
        Account::with(['user'])->where(['type' => 'red_coin', 'fx' => '+'])
            ->where('intro', '<>', '后台充值')
            ->field('uid,amount')
            ->order('create_time', 'desc')
            ->limit(15)
            ->select()
            ->each(function ($item, $key) use (&$record) {
                $city = Area::where('code', $item->user->city)->value('city');
                $mobile = substr_replace($item->user->mobile, '****', 3, 4);
                $amount = $item->amount;
                $record[]['title'] = "恭喜{$city}{$mobile}获得{$amount}奖励";
            });

        return $record;
    }

    public static function _save($param, $admin): array
    {
        parent::startTrans();
        try {
            $param['link'] = $param['video_link'];
            if (isset($param['id']) && $param['id'] > 0) {
                parent::update($param, ['id' => $param['id']]);
            } else {
                $param['business_id'] = $admin['business_id'];
                parent::create($param);
            }

            // todo 视频标签
            if (false !== strpos($param['introduce'], '#')) {
                $tags = substr($param['introduce'], stripos($param['introduce'], "#") + 1);
                $tags = explode('#', $tags);

                foreach ($tags as $tag) {
                    if ($find = VideoTag::where('tag', $tag)->find()) {
                        $find->cites++;
                        $find->save();
                    } else {
                        VideoTag::create([
                            'tag' => $tag
                        ]);
                    }
                }
            }

            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function audit($param, $admin): array
    {
        try {
            $param['admin_id'] = $admin['id'];
            $param['admin_name'] = $admin['admin_name'];
            $param['audit_time'] = time();
            parent::update($param, ['id' => $param['id']]);

            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
